package com.heatup.apt.management.service.course.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.heatup.apt.common.constants.CourseConstants.CourseType;
import com.heatup.apt.common.dao.*;
import com.heatup.apt.common.dao.store.StoreInfoMapper;
import com.heatup.apt.management.service.course.CourseSecretService;
import com.heatup.apt.model.Resource;
import com.heatup.apt.model.ResourceExample;
import com.heatup.apt.model.api.course.CourseSecretModel;
import com.heatup.apt.model.course.CourseCoach;
import com.heatup.apt.model.course.CourseStore;
import com.heatup.apt.model.product.ServicePrice;
import com.heatup.apt.model.product.ServicePriceExample;
import com.heatup.apt.model.store.StoreInfo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class CourseSecretServiceImpl implements CourseSecretService {
	
	
	@Autowired
	private CourseInfoMapper courseInfoMapper;
	
	@Autowired
	private CourseCoachMapper courseCoachMapper;

	@Autowired
	private ServicePriceMapper servicePriceMapper;

	@Autowired
	private CourseSecretDaoMapper courseSecretDaoMapper;

	@Autowired
	private CourseStoreMapper courseStoreMapper;

	@Autowired
	private ResourceMapper resourceMapper;

	@Autowired
	private StoreInfoMapper storeInfoMapper;
	
	
	@Override
	public Map<String, Object> findCourseSercetList(int pageIndex, int pageSize, String nickName, String status, String id) {
		Map<String, Object> param = new HashMap<String, Object>();
        param.put("pageIndex", pageIndex);
        param.put("pageSize", pageSize);
        param.put("coachId", nickName);
        param.put("status", status);
        param.put("courseId", id);
        
        List<CourseSecretModel> list = courseSecretDaoMapper.findCourseResultModels(param);
        for (CourseSecretModel li : list) {
//            CourseStoreExample courseStoreExample = new CourseStoreExample();
//            courseStoreExample.or().andCourseIdEqualTo(li.getId());
//            List<CourseStore> courseStoreslist = courseStoreMapper.selectByExample(courseStoreExample);

            String storeName = "";
            CourseStore courseStoreDB = new CourseStore();
            courseStoreDB.setCourseId(li.getId());
            EntityWrapper<CourseStore> entityWrapper = new EntityWrapper<>(courseStoreDB);
            List<CourseStore> courseStoreslist = courseStoreMapper.selectList(entityWrapper);

            if (courseStoreslist != null) {
                for (CourseStore courseStore : courseStoreslist) {
                    StoreInfo storeInfo = storeInfoMapper.selectById(courseStore.getStoreId());
					if (storeInfo != null && storeInfo.getStoreName() != null) {
						storeName += storeInfo.getStoreName() + "/";
					}
				}
            }
            if (storeName.length() > 0) {
                li.setStoreNames(storeName.substring(0,storeName.lastIndexOf("/")));
            }
        }

        int count = courseSecretDaoMapper.findCourseSecretCount(param);

        Map<String, Object> result = new HashMap<String, Object>();
        result.put("course_sercet_list", list);
        result.put("course_sercet_count", count);
        return result;
	}

	@Override
	public boolean addCourseSecretInfo(CourseSecretModel courseSercet) {
			// 保存课程信息
			String courseAttr =courseSercet.getCourseAttr();
			if(courseAttr!=null && courseAttr.length()>1){
				courseAttr=courseAttr.replaceAll(",", "#");
				courseSercet.setCourseAttr(courseAttr);
			}
			courseSercet.setStatus("2");
			courseInfoMapper.insertSelective(courseSercet);
			
			int courseId = courseSercet.getId();
			// 课程教练信息
			CourseCoach courseCoach = new CourseCoach();
			courseCoach.setCoachId(courseSercet.getCoachId());
			courseCoach.setCourseId(courseId);
			courseCoach.setIsMain("1");  //默认是主教练
			courseCoachMapper.insert(courseCoach);

			// 保存课程门店信息
			String courseStores = courseSercet.getStoreId();   //maxxiang: h5上的select是多选的，
			String[] courseStoreId = courseStores.split(",");

			
			ServicePrice servicePrice = new ServicePrice();
			servicePrice.setCourseId(courseId);
			servicePrice.setPrimePrice(courseSercet.getServicePrice().getPrimePrice());
			servicePrice.setServiceName(courseSercet.getTitle().trim());
			servicePrice.setServiceType(CourseType.private_course.getIndex());
			servicePrice.setPrice(courseSercet.getServicePrice().getPrice());
			servicePrice.setLevel(1);
			if(courseStoreId.length>0){
				servicePrice.setStoreId(Integer.valueOf(courseStoreId[0]));  //私教课新建的时候，默认存第1个门店的id到servicePrice表
			}else{
				servicePrice.setStoreId(0);  
			}
//			servicePrice.setDuration(courseSercet.getPeriods());   //私教这里：Periods与Duration一样 //私教最新的 现在没有节数
			int servicePriceId = servicePriceMapper.insertSelective(servicePrice);

			//保存门店信息
			CourseStore courseStore = null;
			for (String cs : courseStoreId) {
				courseStore = new CourseStore();
				courseStore.setStoreId(Integer.valueOf(cs));
				courseStore.setCourseId(courseId);
				courseStoreMapper.insertSelective(courseStore);
			}

			// 保存二维码图片地址 现在二维码直接从教练表读取了 blank May 5 2017

//			if (StringUtils.isNotBlank(courseSercet.getQunQRCodePic())) {
//				Resource qunQRCodeResource = new Resource();
//				qunQRCodeResource.setParentType("2");
//				qunQRCodeResource.setParentId(courseId);
//				qunQRCodeResource.setResType("1");
//				qunQRCodeResource.setResKey("QRCode");// QR二维码
//				qunQRCodeResource.setTitle("私教课程教练的二维码");
//				qunQRCodeResource.setUrl(courseSercet.getQunQRCodePic());
//				resourceMapper.insertSelective(qunQRCodeResource);
//
//			}

			// 保存视频封面地址
			if (StringUtils.isNotBlank(courseSercet.getUrl())) {
				Resource videoResource = new Resource();
				videoResource.setParentId(courseId);
				videoResource.setParentType("2");
				videoResource.setResType("2");
				videoResource.setUrl(courseSercet.getUrl());
				// videoResource.setPreviewUrl(courseSercet.getVideoPrivewPic());
				videoResource.setLink(courseSercet.getLink());
				videoResource.setResKey("secret_video");// 视频预览
				resourceMapper.insertSelective(videoResource);

			}
			// 保存类别照片地址
			String catePic = courseSercet.getCategoryPic();
			if (catePic.length() > 0) {
				String[] catePics = catePic.split(",");
				Resource catePicResource;
				for (String pic : catePics) {
					catePicResource = new Resource();
					catePicResource.setParentId(courseId);
					catePicResource.setParentType("2");
					catePicResource.setResType("1");
					catePicResource.setUrl(pic);
					catePicResource.setResKey("secret_category");
					resourceMapper.insertSelective(catePicResource);
				}
			}
       
		return true;
	}

	@Override
	public boolean deleteCourseSercet(int id) {
		 if (id <=0)
	            return false;
	        //清理关联表数据....
	        courseCoachMapper.deleteByCourseId(id);
	        servicePriceMapper.deleteByCourseId(id);
	        courseStoreMapper.deleteByCourseId(id);
	        resourceMapper.deleteByCourseId(id);
	        return courseInfoMapper.deleteById(id) > 0;
	
	}

    @Override
    public CourseSecretModel getCourseSecretModelById(int id) {
    	CourseSecretModel courseSecretModel = courseSecretDaoMapper.findCourseSecretById(id);
    	
//    	CourseStoreExample courseStoreExample = new CourseStoreExample();
//    	courseStoreExample.or().andCourseIdEqualTo(id);
//    	List<CourseStore> courseStores = courseStoreMapper.selectByExample(courseStoreExample);


        CourseStore courseStoreDB = new CourseStore();
        courseStoreDB.setCourseId(id);
        EntityWrapper<CourseStore> entityWrapper = new EntityWrapper<>(courseStoreDB);
        List<CourseStore> courseStores = courseStoreMapper.selectList(entityWrapper);

        String storeNames="";
    	String storeIds = "";
    	if(null !=courseStores){
    		
    		for(int i=0; i< courseStores.size();i++){
    			StoreInfo storeInfo = storeInfoMapper.selectById(courseStores.get(i).getStoreId());
    			storeNames+=storeInfo.getStoreName();
    			storeIds += courseStores.get(i).getStoreId();
    			
    			if (i< (courseStores.size()-1)){  //最后一个不再加#号
    				storeNames = storeNames + "#";
    				storeIds = storeIds + "#";
    			}
    		}
    	}
    
    	courseSecretModel.setStoreNames(storeNames);
    	courseSecretModel.setStoreIdList(storeIds);
    	
    	ResourceExample example = new ResourceExample();
    	example.or().andParentIdEqualTo(id);
    	List<Resource> resources = resourceMapper.selectByExample(example);
    	if (resources != null && resources.size() > 0) {
    		 StringBuilder sCatePic = new StringBuilder();
             for (Resource resource : resources) {

                 if (StringUtils.isNotBlank(resource.getResKey()) && resource.getResKey().equalsIgnoreCase("QRCode")) {
                	 courseSecretModel.setQunQRCodePic(resource.getUrl());
                 }
                 if (StringUtils.isNotBlank(resource.getResKey()) && resource.getResKey().equalsIgnoreCase("secret_video")) {
                	 courseSecretModel.setUrl(resource.getUrl());
                	 courseSecretModel.setLink(resource.getLink());
                 }
                 if (StringUtils.isNotBlank(resource.getResKey()) && resource.getResKey().equalsIgnoreCase("secret_category")) {
                     if (sCatePic.length() <= 0) {
                         sCatePic.append(resource.getUrl());
                     } else {
                         sCatePic.append("," + resource.getUrl());
                     }
                 }
             }

             if (sCatePic.length() > 0) {
            	 courseSecretModel.setCategoryPic(sCatePic.toString());
             }
         }
    	
        return courseSecretModel;
    }

	@Override
	public boolean updateCourseSecretInfo(CourseSecretModel courseSercet) {
		
		if(courseSercet!=null){
			int courseId= courseSercet.getId();
			String courseAttr =courseSercet.getCourseAttr();
			courseSercet.setStatus("2");
			if(courseAttr!=null && courseAttr.length()>1){
				courseAttr=courseAttr.replaceAll(",", "#");
				courseSercet.setCourseAttr(courseAttr);
			}
			//更新课程基本信息
			courseInfoMapper.updateSelectiveById(courseSercet);
			
			//更新课程教练信息
			CourseCoach courseCoach= new CourseCoach();
			courseCoach.setIsMain("1");  //默认是主教练
			courseCoach.setCoachId(courseSercet.getCoachId());
			courseCoach.setCourseId(courseId);
			courseCoachMapper.updateByCourseId(courseCoach);

			// 保存课程门店信息
			String courseStores = courseSercet.getStoreId();
			String[] courseStoreId = courseStores.split(",");

			
			//课程价格信息
			ServicePriceExample servicePriceExample  = new ServicePriceExample();
			servicePriceExample.or().andCourseIdEqualTo(courseSercet.getId()).andServiceTypeEqualTo(2);
			List<ServicePrice> servicePrices = servicePriceMapper.selectByExample(servicePriceExample);
			if(null != servicePrices){
				for(ServicePrice servicePrice :servicePrices){
					servicePrice.setServiceName(courseSercet.getTitle());
					servicePrice.setPrimePrice(courseSercet.getServicePrice().getPrimePrice());
					servicePrice.setPrice(courseSercet.getServicePrice().getPrice());
//					servicePrice.setDuration(courseSercet.getPeriods());   //私教: course_info表的periods字段与 service_price表的duration字段要同步。//私教现在没有节数
					
					if(courseStoreId.length>0){
						servicePrice.setStoreId(Integer.valueOf(courseStoreId[0]));  //私教课新建的时候，默认存第1个门店的id到servicePrice表
					}else{
						servicePrice.setStoreId(0);  
					}

					servicePriceMapper.updateByPrimaryKeySelective(servicePrice);
					break;  //必须只有一条
				}
			}
			
			courseStoreMapper.deleteByCourseId(courseId);
			CourseStore courseStore = null;
			for (String cs : courseStoreId) {
				courseStore = new CourseStore();
				courseStore.setStoreId(Integer.valueOf(cs));
				courseStore.setCourseId(courseId);
				courseStoreMapper.insertSelective(courseStore);
			}
			
			//课程相关删除资源信息
			resourceMapper.deleteByCourseId(courseId);
			// 保存二维码图片地址 现在二维码直接从教练表读取了 blank May 5 2017
//			if (StringUtils.isNotBlank(courseSercet.getQunQRCodePic())) {
//				Resource qunQRCodeResource = new Resource();
//				qunQRCodeResource.setParentType("2");
//				qunQRCodeResource.setParentId(courseId);
//				qunQRCodeResource.setResType("1");
//				qunQRCodeResource.setResKey("QRCode");// QR二维码.统一用这个表示
//				qunQRCodeResource.setTitle("私教课程教练的二维码");
//				qunQRCodeResource.setUrl(courseSercet.getQunQRCodePic());
//				resourceMapper.insertSelective(qunQRCodeResource);
//
//			}
			// 保存视频封面地址
			if (StringUtils.isNotBlank(courseSercet.getUrl())) {
				Resource videoResource = new Resource();
				videoResource.setParentId(courseId);
				videoResource.setParentType("2");
				videoResource.setResType("2");
				videoResource.setUrl(courseSercet.getUrl());
				// videoResource.setPreviewUrl(courseSercet.getVideoPrivewPic());
				videoResource.setLink(courseSercet.getLink());
				videoResource.setResKey("secret_video");// 视频预览
				resourceMapper.insertSelective(videoResource);

			}
			// 保存类别照片地址
			String catePic = courseSercet.getCategoryPic();
			if (catePic.length() > 0) {
				String[] catePics = catePic.split(",");
				Resource catePicResource;
				for (String pic : catePics) {
					catePicResource = new Resource();
					catePicResource.setParentId(courseId);
					catePicResource.setParentType("2");
					catePicResource.setResType("1");
					catePicResource.setUrl(pic);
					catePicResource.setResKey("secret_category");
					resourceMapper.insertSelective(catePicResource);
				}
			}
		
			
		}
		
		return true;
	}

}
